<template>
	<view>
		<view class="bgw" id="topBox">
			<view class="" v-if="isShowCusTabs">
				<u-tabs :list="cusTabs" @click="cusTabClick" :current="cusTabbarCurrent" :activeStyle="activeStyle"
					lineColor="#675f91">
					<view slot="right" style="padding-right: 10px;">
						<view class="flex" style="justify-content: flex-end;">
							<picker mode="date" :value="need_date" :start="startDate" :end="endDate" @change="bindDateChange">
								<u-button type="info" size="small" :text="need_date"></u-button>
							</picker>
							<view class="ml10" style="min-width: 30px;">
								<u-button type="info" icon="setting" size="small" text="显示"
									@click="openSetting"></u-button>
							</view>
						</view>
					</view>
				</u-tabs>
			</view>
			<view class="" v-if="!isShowCusTabs">
				<view class="blank10"></view>
				<view class="flex" style="padding-right: 10px;">
					<view class="flex-1"></view>
					<view class="flex" style="justify-content: flex-end;">
						<picker mode="date" :value="need_date" :start="startDate" :end="endDate" @change="bindDateChange">
							<u-button type="info" size="small" :text="need_date"></u-button>
						</picker>
						<view class="ml10" style="min-width: 30px;">
							<u-button type="info" icon="setting" size="small" text="显示" style="min-width: 30px;" @click="openSetting"></u-button>
							</view>
					</view>
				</view>

				<view class="blank10"></view>
			</view>
			<u-line></u-line>
			<search @choose="chooseSearch" page="food" :data="scrollData" namekey="mname" @recorder="openRecorderPopup"></search>
			<u-line></u-line>
		</view>
		<template v-if="scrollHeight && scrollData.length>0">
			<purchaseMaterialList ref="purchaseMaterialList" :data="scrollData" :menu="scrollMenu" :height="scrollHeight" :scroll_id="scrollViewId" :set="settingObj" @scrollViewIdDone="scrollViewIdDone" page="food"
				@updata="updataBagList" :init_value="scrollInitValue" :loadtime="loadtime"></purchaseMaterialList>
		</template>
		<view class="fixed-bottom bgw" id="bottomBox">
			<u-line></u-line>
			<view class="flex">
				<view class="bag-btn flex justify-center" @click="openBag">
					<u-badge type="error" :isDot="true" :absolute="true" :offset="[0,0]" v-if="bagList.length>0"></u-badge>
					<u-icon name="bag-fill" size="20" color="#675f91"></u-icon>
				</view>
				<view class="flex-1" v-if="bagList.length>0">
					共 <text class="font-bold">{{bagList.length}}</text>
					种食材
				</view>
				<view class="flex-1 text-red" v-else>
					请添加食材
				</view>
				<view :class="bagList.length == 0? 'disabled':''" class="save-btn ml15" @click="save">
					保存
				</view>
				<!-- bagList.length -->
			</view>
		</view>

		<u-popup :show="settingPopupShow" @close="settingPopupClose" @open="settingPopupOpen" mode="top" :closeable="true">
			<view class="flex justify-center" style="background-color: #f5f5f5;height: 44px;">
				<view>
					设置列表显示内容
				</view>
			</view>
			<view class="blank20"></view>
			<view class="wrapper">
				<u-checkbox-group v-model="setting" placement="row">
					<view class="flex" style="flex-wrap: wrap;">
						<template v-for="v in settingConfig">
							<view class="" style="margin: 15upx;">
								<u-checkbox activeColor="#675f91" :label="v.label" :name="v.name"></u-checkbox>
							</view>
						</template>
					</view>
				</u-checkbox-group>
			</view>
			<view class="blank20"></view>
			<view class="wrapper" style="background-color: #f5f5f5;">
				<view class="blank20"></view>
				<u-row justify="space-between" gutter="10">
					<u-col span="6">
						<u-button type="info" text="关闭" @click="closeSetting"></u-button>
					</u-col>
					<u-col span="6">
						<u-button type="primary" text="确定" @click="saveSetting"></u-button>
					</u-col>
				</u-row>
			
				<view class="blank20"></view>
			</view>
		</u-popup>
		<u-popup :show="popupShow" @close="popupClose" @open="popupOpen" mode="bottom" :closeable="true">
			<view class="flex justify-center" style="background-color: #f5f5f5;height: 44px;">
				<view>
					已添加的食材
				</view>
			</view>
			<scroll-view scroll-y scroll-with-animation class="popup-scroll">
				<view class="">
					<template v-for="v in bagList">
						<view class="wrapper">
							<view class="blank10"></view>
							<view class="flex">
								<view class="flex-1">
									{{v.name}}
								</view>
								<view style="width: 150upx;">
									{{v.value}}
								</view>
								<view class="text-gray font-24" style="width: 200upx;" v-if="isShowCusTabs">
									{{v.tips}}
								</view>
							</view>
							<view class="blank10"></view>
							<u-line color="#e6e6e6"></u-line>
						</view>
					</template>
				</view>
			</scroll-view>
			<view class="wrapper" style="background-color: #f5f5f5;">
				<view class="blank20"></view>
				<u-row justify="space-between" gutter="10">
					<u-col span="6">
						<u-button type="info" text="关闭" @click="popupShow = false"></u-button>
					</u-col>
					<u-col span="6">
						<u-button type="primary" :disabled="bagList.length == 0" text="保存" @click="save"></u-button>
					</u-col>
				</u-row>

				<view class="blank20"></view>
			</view>
		</u-popup>
		<recorder-popup :open="recorderPopupOpen" @close="closeRecorderPopup" @add="addRecorderPopup" :data="scrollData" page="food"></recorder-popup>
	</view>
</template>

<script>
	import search from "@/components/search.vue";
	import purchaseMaterialList from "@/pagesA/components/purchase-material-list/purchase-material-list.vue";
	import recorderPopup from "@/pagesA/components/recorder-popup/recorder-popup.vue";
	
	import {
		pr_groupby_and_convert,
		purchase_request_draft,
		purchase_request_edit,
		purchase_request_require_handin,
		purchase_record_handin,
		material_static_data
	} from '@/common/api.js';

	let today = new Date();
	let date = new Date(today.getTime() + (24 * 60 * 60 * 1000 * 1)); //明天
	let year_month_day = `${date.getFullYear()}` + `-` + `${date.getMonth()+1}`.padStart(2, '0') + `-` +
		`${date.getDate()}`.padStart(2, '0');
	let date_end = new Date(today.getTime() + (24 * 60 * 60 * 1000 * 7));
	let year_month_day_end = `${date_end.getFullYear()}` + `-` + `${date_end.getMonth()+1}`.padStart(2, '0') + `-` +
		`${date_end.getDate()}`.padStart(2, '0');

	export default {
		components: {
			search,
			purchaseMaterialList,
			recorderPopup
		},
		data() {
			return {
				id: 0,
				popupShow: false,
				titleStyle: {
					color: '#ffffff'
				},
				activeStyle: {
					color: '#675f91'
				},
				cusTabs: [],
				cusTabbarCurrent: 0,
				allValueObj: {},
				tabbar: [],
				need_day: year_month_day,
				need_date: year_month_day,
				bagList: [],
				isShowCusTabs: false,
				purchase_record_list: [],
				scrollViewId: 0,
				scrollHeight: '',
				scrollData: [],
				scrollMenu: [],
				scrollDataObj:{},
				scrollInitValue: [],
				loadtime: 0,
				settingPopupShow: false,
				old_setting:[],
				setting: [
					'purchase_unit_id','stock_qty_unit','main_price','brand','spec','model','default_msupplier_id'
				],
				settingObj:{},
				settingConfig: [{
						label: '单位',
						name: 'purchase_unit_id'
					},
					{
						label: '库存',
						name: 'stock_qty_unit'
					},
					{
						label: '单价',
						name: 'main_price'
					},
					{
						label: '品牌',
						name: 'brand'
					},
					{
						label: '规格',
						name: 'spec'
					},
					{
						label: '型号',
						name: 'model'
					},
					{
						label: '默认供应商',
						name: 'default_msupplier_id'
					},
				],
				recorderPopupOpen:false,

			}
		},
		computed: {
			startDate() {
				return year_month_day;
				// return this.getDate('start');
			},
			endDate() {
				return year_month_day_end;
			}
		},
		methods: {
			openRecorderPopup(){
				console.log('openRecorderPopup');
				this.recorderPopupOpen = true;
			},
			closeRecorderPopup(){
				this.recorderPopupOpen = false;
			},
			addRecorderPopup(data){
				// console.log(data);
				let {material_id,unit_id,qty} = data;
				let cusTabbarCurrent = this.cusTabbarCurrent;
				if(!this.allValueObj[cusTabbarCurrent]){
					this.allValueObj[cusTabbarCurrent] = [];
				}
				let item = this.allValueObj[cusTabbarCurrent].find(v=>v.id == material_id);
				if(item){
					item.value += qty
				}else{
					let material = this.scrollDataObj[material_id];
					this.allValueObj[this.cusTabbarCurrent].push({
						id: material_id,
						name: material.mname,
						value: qty,
						unit_id: material.purchase_unit_id[0],
						unit_name: material.purchase_unit_id[1],
						price: material.purchase_unit_price,
						msupplier_id: material.default_msupplier_id[0],
						is_quote: material.is_quote,
						mm_id: material.mm_id[0]
					})
				}
				this.scrollInitValue = this.allValueObj[this.cusTabbarCurrent] || [];
				this.$refs.purchaseMaterialList.updataValueObj(0,this.scrollInitValue);
				this.updataBagList(this.scrollInitValue);
				// this.closeRecorderPopup();
				this.chooseSearch(material_id);
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindDateChange: function(e) {
				this.need_date = e.detail.value;
			},
			openBag() {
				// this.updataBagList();
				this.popupShow = true;
			},
			openSetting() {
				this.settingPopupShow = true;
			},
			settingPopupClose() {
				this.closeSetting();
			},
			settingPopupOpen() {

			},
			saveSetting(){
				this.updataSettingObj();
				this.settingPopupShow = false;
			},
			updataSettingObj(){
				uni.setStorageSync('food-setting', this.setting);
				let settingObj = {};
				this.setting.forEach(v=>{
					settingObj[v] = true;
				})
				this.settingObj = settingObj;
				this.old_setting = this.setting;
			},
			closeSetting(){
				this.setting = this.old_setting;
				this.settingPopupShow = false;
			},
			popupClose() {
				this.popupShow = false;
			},
			popupOpen() {

			},
			cusTabClick(e) {
				if(this.cusTabbarCurrent == e.index){
					return;
				}
				this.cusTabbarCurrent = e.index;
				this.scrollInitValue = this.allValueObj[this.cusTabbarCurrent] || [];
				this.$refs.purchaseMaterialList.updataValueObj(0,this.scrollInitValue)
			},
			chooseSearch(id) {
				this.scrollViewId = id;
			},
			scrollViewIdDone(){
				this.scrollViewId = 0;
			},
			set_purchase_record_list() {
				let purchase_record_list = [];
				for (let cusTabbarCurrent in this.allValueObj) {
					this.allValueObj[cusTabbarCurrent].forEach(v => {
						let id = v.id;
						let cus_sub_id = this.cusTabs[cusTabbarCurrent].id;
						let purchase_unit_price = v.price;
						let purchase_unit_id = v.unit_id;
						let purchase_unit_qty = v.value;
						let need_date = this.need_date;
						let msupplier_id = v.msupplier_id;
						let item = {
							'id':Number(id),
							'cus_sub_id': cus_sub_id,
							'purchase_unit_price': purchase_unit_price,
							'purchase_unit_id': purchase_unit_id,
							'purchase_unit_qty': purchase_unit_qty,
							'need_date': need_date,
							'msupplier_id': msupplier_id,
							'is_quote':v.is_quote,
							'mm_id':v.mm_id
						};
						if(!v.is_quote){
							item.material_id = Number(id);
						}else{
							item.material_id = 0;
						}
						purchase_record_list.push(item);
					})
				}
				this.purchase_record_list = purchase_record_list;

				//缓存
				let id = this.id;
				uni.setStorage({
					key: 'purchase_record_list_' + id,
					data: purchase_record_list,
					success: function() {
						// console.log('success');
					}
				});
			},
			save() {
				if (this.bagList.length == 0) {
					uni.$u.toast('请添加食材');
					return;
				}
				this.set_purchase_record_list();

				if (this.id == 0) {
					uni.showLoading({
						title: '加载中'
					});
					pr_groupby_and_convert({
						pr_id: this.id,
						pr_detail_list: this.purchase_record_list
					}).then((res) => {
						// console.log(res);
						if (res.result.length == 0) {
							uni.$u.toast('无汇总');
							return;
						}
						uni.$u.toast('操作成功');
						uni.setStorage({
							key: 'mm_list_0',
							data: res.result,
							success: function() {
								// console.log('success');
							}
						});
						setTimeout(() => {
							this.nav('/purchaseDetail/purchaseDraft?id=0');
						}, 2000)
					}).catch(() => {


					}).finally(() => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
					})

				} else {
					if (this.status == 's2_accepted') {
						uni.$u.toast('已批准，不可修改');
						return;
					}
					if (this.status == 's3_rejected') {
						uni.$u.toast('已驳回，不可修改');
						return;
					}
					if (this.status == 's4_closed') {
						uni.$u.toast('已下单，不可修改');
						return;
					}
					// pr_detail_list
					uni.showLoading({
						title: '加载中'
					});
					purchase_request_require_handin({
						pr_id: this.id,
						pr_detail_list: this.purchase_record_list
					}).then((res) => {
						uni.$u.toast('保存成功');
						setTimeout(() => {
							uni.$u.route({
								type: 'navigateBack'
							})
						}, 2000)
					}).catch(() => {

					}).finally(() => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
					})
				}
				// if (this.status) {
				// } else {
				// }
			},
			updataBagList(bags) {
				// console.log(bags);

				let cusTabbarCurrent = this.cusTabbarCurrent;
				this.allValueObj[cusTabbarCurrent] = bags;
				let bagList = [];
				let bagObj = {};
				for (let i in this.allValueObj) {
					this.allValueObj[i].forEach(v => {
						let id = v.id;
						!bagObj[id] && (bagObj[id] = {
							...v,
							value: 0,
							cus: [],
							valueArr: []
						});
						bagObj[id].value += v.value;
						bagObj[id].cus.push(i);
						bagObj[id].valueArr.push(v.value);
					})
				}

				for (let id in bagObj) {
					let tips = [];
					bagObj[id].cus.forEach((v, i) => {
						v = Number(v);
						tips.push(`${this.cusTabs[v].name}(${bagObj[id].valueArr[i]})`)
					})

					bagList.push({
						...bagObj[id],
						tips: tips.join('，')
					});
				}
				this.bagList = bagList;
			},
			getData_callback(res) {
				let { material_item,cus_sub_category } = res.result;
				let update_value = {
					updateArr:material_item.update,
					delIds:material_item.unlink
				};
				
				this.$store.commit('update_material_item', update_value);
				let all_material_item = this.$store.getters.get_material_item;
				this.scrollData = all_material_item ||[];
				this.scrollDataObj = this.toObj(this.scrollData||[],'id');
				// this.material_item = all_material_item;
				
				// console.log('food');
				// console.log(this.scrollData);

				// this.scrollData = material_item || [];
				// this.scrollDataObj = this.toObj(material_item||[],'id');
				
				// this.scrollMenu = material_purchase_category || [];

				this.isShowCusTabs = cus_sub_category.length > 0;
				if (this.isShowCusTabs) {
					this.cusTabs = cus_sub_category;
				} else {
					this.cusTabs = [{
						id: 0,
						name: '默认'
					}];
				}
				this.loadtime = new Date().getTime();

				this.$nextTick(() => {
					this.getScrollHeight();
				})
				// this.updataTabbar();
				// this.updataList();
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				purchase_request_edit({
					pr_id: this.id,
					day: this.need_day
				}).then((res) => {
					this.getData_callback(res);
					let {
						pr_record_detail
					} = res.result;
					// this.allValueObj[i][id]
					this.allValueObj = {};
					pr_record_detail.forEach(v => {
						let _index = 0;
						if (v.cus_sub_id && v.cus_sub_id[0]) {
							let cus = this.cusTabs.find(c => c.id == v.cus_sub_id[0]);
							if (!cus) {
								let _length = this.cusTabs.push({
									id: v.cus_sub_id[0],
									name: v.cus_sub_id[1]
								})
								_index = _length - 1;
							}
						}
						if (!this.allValueObj[_index]) {
							this.allValueObj[_index] = {};
						}
						this.allValueObj[_index][v.material_id[0]] = v.purchase_unit_qty
					})

					this.valueObj = this.allValueObj[this.cusTabbarCurrent] || {};

					this.isShowCusTabs = this.cusTabs.length > 1;
					// console.log(this.allValueObj);
					this.updataBagList();

				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			getData0() {
				uni.showLoading({
					title: '加载中'
				});
				purchase_request_draft({
					need_day: this.need_day
				}).then((res) => {
					this.getData_callback(res);
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			getScrollHeight() {
				uni.createSelectorQuery().select('#topBox').boundingClientRect(data => {
					let topBoxHeght = data.height;
					uni.createSelectorQuery().select('#bottomBox').boundingClientRect(data2 => {
						let bottomBoxHeight = data2.height;
						this.scrollHeight = this.getClineHeight() - topBoxHeght - bottomBoxHeight;
					}).exec()
				}).exec()
			},
		},
		onLoad(d) {
			this.status = d.status;
			this.id = Number(d.id) || 0;
			if (this.id == 0) {
				this.getData0();
			} else {
				this.getData();
			}
		},
		onShow() {
			//从缓存读取 todo
			try{
				this.setting = uni.getStorageSync('food-setting')||[];
				this.updataSettingObj();
			}catch(e){}
			uni.$off('refresh_food');
			uni.$once('refresh_food',()=>{
				if (this.id == 0) {
					this.getData0();
				} else {
					this.getData();
				}
			})
			
		},
		onReady() {
			if (this.id == 0) {
				uni.setNavigationBarTitle({
					title: '生成采购单'
				});
			} else {
				uni.setNavigationBarTitle({
					title: '窗口明细'
				});
			}
		},
		onPullDownRefresh() {
			this.getData();
		}
	}
</script>

<style lang="scss" scoped>
	@import './food.scss';
</style>